package cloud.demo.user.interfaces.web;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;

import cloud.demo.user.domain.model.User;
import cloud.demo.user.domain.service.UserService;
@RestController
public class UserController {

	@Autowired
	private UserService userService;
	
	@GetMapping("/user/{id}")
	public User getUserById(@PathVariable("id")Integer id) {
		User user = userService.getUserById(id);
		user.setId(1);
		user.setName("zhao liu");
		return user;
	}
	
	@GetMapping("/login/{id}")
	public String login(@PathVariable("id")Integer id, HttpSession session) {
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		session.setAttribute("user_token", token);
		return  "user1 =  "+ token;
	}
	
	@GetMapping("/token")
	public String getToken(HttpSession session, HttpServletRequest req) throws JsonProcessingException {
		Cookie[] cookies = req.getCookies();
    	System.out.println(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(cookies));
		System.out.println("user1 session_id = "+session.getId());
		return "user1 token = "+(String)session.getAttribute("user_token");
	}
}
